package com.tvunetworks.center.device.controller;

import com.alibaba.fastjson.JSON;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.device.annotation.Logined;
import com.tvunetworks.center.device.model.router.Peer;
import com.tvunetworks.center.device.model.router.SlotMsg;
import com.tvunetworks.center.device.service.RouterService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @program: tvucc-device
 * @author lebronchen
 * @create: 2019-03-15 13:21
 **/
@Slf4j
@RestController
@RequestMapping("/router")
public class RouterMonitorController {
    @Value("${slotsStatusKey}")
    private String slotsStatusKey;
    @Value("${dashboardUrl}")
    private String dashboardUrl;
    @Resource(name = "redisDevTemplate")
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RouterService routerService;

    /**
     *
     * @param loginUser loginUser
     * @return Result
     */
    @RequestMapping("/routerList")
    public Result<Object> routerList(@Logined LoginUser loginUser){
        if(loginUser==null){
            return ResultUtil.noLogin();
        }
        List<Peer> peerList =null;
        try {
             peerList = routerService.findRoutlistfromTPC(loginUser.getId());
        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        return ResultUtil.success(peerList);
    }

    /**
     *
     * @param loginUser loginUser
     * @param peerId peerId
     * @return Result Result
     */
    @RequestMapping("/findSlotsCheckStatus")
    public Result<Object> findSlotsCheckStatus(@Logined LoginUser loginUser, @RequestParam("peerId") String peerId){
        if(loginUser==null){
            return ResultUtil.noLogin();
        }
        String slotsInfo ="";
        try {
             slotsInfo =  routerService.findSlotsCheckStatus(peerId);
            if(StringUtils.isEmpty(slotsInfo)){
                slotsInfo = "{\"peerid\":\""+peerId+"\",\"slots\":[{}]}";
            }
        } catch (Exception e) {
            log.error("==查询slots check状态异常==Class:RouterAction;method:findSlotsCheckStatus;Line:154;error:"+e.getMessage().toString());
        }
        return ResultUtil.success(slotsInfo);
    }

    /**
     *
     * @param loginUser loginUser
     * @return Result
     */
    @RequestMapping("/getRouterSelectRecord")
    public Result<Object> getRouterSelectRecord(@Logined LoginUser loginUser){
        if(loginUser==null){
            return ResultUtil.noLogin();
        }
        Map object = new HashMap();
        String recordid ="";
        try {
             recordid = routerService.getRouterSelectRecord(loginUser.getId());

            if(recordid ==null){
                recordid="";
            }
            object.put("userid",loginUser.getId());
            object.put("peerid",recordid);
        } catch (Exception e) {
            log.error("==查询slots check状态异常==Class:RouterAction;method:findSlotsCheckStatus;Line:154;error:"+e.getMessage().toString());
        }
        return ResultUtil.success(object);
    }

    /**
     *
     * @param loginUser loginUser
     * @param slotMsg slotMsg
     * @return Result
     */
    @RequestMapping("/sendSlotMsgPipe")
    public Result<Object> sendSlotMsgPipe(@Logined LoginUser loginUser, @RequestBody SlotMsg slotMsg){
        if(loginUser==null){
            return ResultUtil.noLogin();
        }
        if(slotMsg.getCmd() ==null ||slotMsg.getSlotId() ==null ||slotMsg.getPeerId() ==null){
            log.error("==msgpipe 发送消息给T 中有为空的参数==Class:RouterAction;method:sendMsgPipe;Line:138");
            return ResultUtil.paramError();
        }
        Long timestamp = System.currentTimeMillis();
        try {
            routerService.sendMsgPipe(slotMsg.getPeerId(),slotMsg.getSlotId(),slotMsg.getCmd().toUpperCase(),timestamp);
        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        String key ="";
        if("STOP".equals(slotMsg.getCmd().toUpperCase())){
            key = slotsStatusKey+"_STOP_"+slotMsg.getPeerId()+"_"+timestamp;
        }else if("START".equals(slotMsg.getCmd().toUpperCase())){
            key = slotsStatusKey+"_START_"+slotMsg.getPeerId()+"_"+timestamp;
        }else{
            key = slotsStatusKey+"_RESET_"+slotMsg.getPeerId()+"_"+timestamp;
        }
        String resultValue ="";
        while(true){
            resultValue = stringRedisTemplate.opsForValue().get(key);
            if(StringUtils.isEmpty(resultValue)){
                break;
            }
            if(System.currentTimeMillis()-timestamp>5*1000){
                break;
            }


        }
        Map object =  new HashMap<>();
        if(StringUtils.isEmpty(resultValue)){

            object.put("result","request time out");
            resultValue = object.toString();
        }
        return ResultUtil.success(resultValue);
    }
//    @RequestMapping("/task")

    /**
     * 定时任务
     */
    @Scheduled(initialDelay = 3000, fixedDelayString = "1000")
    public void task(){
        String taskId = UUID.randomUUID().toString();
        try {
            log.info("routerService.getStatusXmlTask start taskId:{}",taskId);
            routerService.getStatusXmlTask();
        } catch (Exception e) {
            log.error("routerService.getStatusXmlTask is error:{}",e);
        }
        log.info("routerService.getStatusXmlTask end taskId:{}",taskId);
    }

    /**
     *
     * @param loginUser loginUser
     * @return Result
     */
    @RequestMapping("/redirectJson")
    public Result<Object> redirectJson(@Logined LoginUser loginUser){
        if(loginUser==null){
            return ResultUtil.noLogin();
        }
        JSONObject object = new JSONObject();
        object.put("dashboard",dashboardUrl);
        String json = JSON.toJSONString(object);
        return ResultUtil.success(json);
    }

}
